package offer;

/**
 * 剑指 Offer 12. 矩阵中的路径
 */
public class Exist {
    int n;
    int m;
    int len;

    public static void main(String[] args) {

    }

    public boolean exist(char[][] board, String word) {
        this.n = board.length;
        this.m = board[0].length;
        this.len = word.length();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (dsf(board, i, j, word, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dsf(char[][] board, int i, int j, String word, int k) {
        //判断是否越界，已经访问过或者不匹配
        if (i < 0 || i >= n || j < 0 || j >= m || board[i][j] != word.charAt(k)) {
            return false;
        }
        //如果输入的字符串长度已经等于k，呢么说明已经匹配完整
        if (k == len - 1) {
            return true;
        }
        //代表这个元素已经被访问过，不再重复访问
        board[i][j] = '#';
        boolean res = dsf(board, i, j - 1, word, k + 1)
                || dsf(board, i + 1, j, word, k + 1)
                || dsf(board, i, j + 1, word, k + 1)
                || dsf(board, i - 1, j, word, k + 1);
        //回退到上一个字符
        board[i][j] = word.charAt(k);
        return res;
    }
}
